package com.tm.controller;

import java.util.Collections;
import java.util.List;
import java.util.Vector;

import com.google.appengine.api.datastore.QueryResultIterator;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
import com.tm.fundament.Initializer;
import com.tm.pojo.Instrument;

public class InstrumentController {
	private static InstrumentController ic = null;
	private List<Instrument> instruments = new Vector<Instrument>();
	
	private InstrumentController() {
		Initializer.getInstance().init();
		loadStoredInstruments();
	}
	
	public static InstrumentController getInstance() {
		if (ic == null) {
			ic = new InstrumentController();
		}
		return ic;
	}
	
	private void loadStoredInstruments() {
		Objectify ofy = ObjectifyService.begin();
		
		Query<Instrument> q = ofy.query(Instrument.class);
		QueryResultIterator<Instrument> i = q.iterator();
		while (i.hasNext()) {
			Instrument in = i.next();
			instruments.add(in);
		}
		Collections.sort(instruments);
	}
	
	public Instrument saveNewInstrument(Instrument i) {
		Objectify ofy = ObjectifyService.begin();
		ofy.put(i);
		instruments.add(i);
		Collections.sort(instruments);
		return i;
	}
	
	public List<Instrument> getInstruments() {
		return instruments;
	}
	
	public void deleteInstrument(String strInstrumentId) {
		if (strInstrumentId != null) {
			try {
				Long id = Long.parseLong(strInstrumentId);
				Objectify ofy = ObjectifyService.begin();
				ofy.delete(new Key<Instrument>(Instrument.class, id));
				Instrument i = new Instrument();
				i.setInstrumentId((long)id);
				instruments.remove(i);
			} catch (Throwable e) {
				// ignore
			}
		}
	}
	
	public Instrument getInstrument(Long instrumentId) {
		Objectify ofy = ObjectifyService.begin();
		return ofy.get(Instrument.class, instrumentId);
	}
}
